/* $Id: LocalizationModel.java 101 2010-12-26 21:25:55Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models;

import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import alt.djudge.frontend.server.datatypes.LocaleEntry;
import alt.djudge.frontend.server.datatypes.UserEntry;

/*import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle.Control;
*/
// FIXME: dirty hack
/**
 * JDK 6's {@link ResourceBundle.Control} subclass that allows
 * loading of bundles in XML format.
 * The bundles are searched first as Java classes, then as
 * properties files (these two methods are the standard
 * search mechanism of ResourceBundle), then as XML properties
 * files.
 * The filename extension of the XML properties files is assumed
 * to be *.properties.xml
 */
/*class ExtendedControl extends ResourceBundle.Control
{
    private static final String FORMAT_XML_SUFFIX = "properties";
    private static final String FORMAT_XML = "java." + FORMAT_XML_SUFFIX;
    private static final List<String> FORMATS;
    static
    {
        List<String> formats = new ArrayList<String>(FORMAT_DEFAULT);
        formats.add(FORMAT_XML);
        FORMATS = Collections.unmodifiableList(formats);
    }

    @Override
    public List<String> getFormats(String baseName)
    {
        return FORMATS;
    }

    public ResourceBundle newBundle(String baseName, Locale locale,
                                    String format, ClassLoader loader,
                                    boolean reload)
            throws IllegalAccessException, InstantiationException, IOException
    {
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, FORMAT_XML_SUFFIX);
        final URL resourceURL = loader.getResource(resourceName);
        if (resourceURL == null) return null;

        InputStream stream = getprivateResourceInputStream(resourceURL, reload);

        try
        {
        	PropertyResourceBundle result = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
            return result;
        }
        finally
        {
            stream.close();
        }
    }

    private InputStream getprivateResourceInputStream(final URL resourceURL,
                                               boolean reload)
            throws IOException
    {
        if (!reload) return resourceURL.openStream();

        try
        {
            // This permission has already been checked by
            // ClassLoader.getResource(String), which will return null
            // in case the code has not enough privileges.
            return AccessController.doPrivileged(
                    new PrivilegedExceptionAction<InputStream>()
            {
                public InputStream run() throws IOException
                {
                    URLConnection connection = resourceURL.openConnection();
                    connection.setUseCaches(false);
                    return connection.getInputStream();
                }
            });
        }
        catch (PrivilegedActionException x)
        {
            throw (IOException)x.getCause();
        }
    }

    / **
     * ResourceBundle that loads definitions from an XML properties file.
     * /
    public static class PropertyXMLResourceBundle extends ResourceBundle
    {
        private final Properties properties = new Properties();

        public void load(InputStream stream) throws IOException
        {
            properties.loadFromXML(stream);
        }

        protected Object handleGetObject(String key)
        {
            return properties.getProperty(key);
        }

        public Enumeration<String> getKeys()
        {
            final Enumeration<Object> keys = properties.keys();
            return new Enumeration<String>()
            {
                public boolean hasMoreElements()
                {
                    return keys.hasMoreElements();
                }

                public String nextElement()
                {
                    return (String)keys.nextElement();
                }
            };
        }
    }
}*/

public class LocalizationModel
{
	private static Logger log = Logger.getLogger(LocalizationModel.class);
	
	public static ResourceBundle getResourceBundle()
	{
		return ResourceBundle.getBundle("djudge");
	}
	
	public static ResourceBundle getResourceBundle(Locale locale)
	{
		return ResourceBundle.getBundle("djudge", locale);
	}
	
	public static ResourceBundle getResourceBundle(LocaleEntry locale)
	{
		log.debug("Request for locale: " + locale.getJavaLocale());
		return ResourceBundle.getBundle("djudge", new Locale(locale.getJavaLocale()));
	}
	
	public static void setUserLocale(HttpServletRequest request, HttpServletResponse response, String localeJavaSid)
	{
		LocaleEntry newLocale = LocalesModel.getEntryByJavaSid(localeJavaSid);
		if (null != newLocale)
		{
			RequestStorageModel.saveData("locale", localeJavaSid, request, response);
		}
	}
	
	public static LocaleEntry getUserLocale(UserEntry user, HttpServletRequest request)
	{
		LocaleEntry locale = null;
		// search for locale in request && cookies
		for (String localeStr : new String[] {request.getParameter("setlocale"), request.getParameter("locale"), RequestStorageModel.getData("locale", request)})
			if (null != localeStr)
			{
				LocaleEntry t = LocalesModel.getEntryByJavaSid(localeStr);
				if (null != t && null == locale)
					locale = t;
			}
		// if no locale if set then return default locale
		if (null == locale)
			locale = LocalesModel.getDefaultEntry();
		return locale;
	}
	
}
